package com.ly.hotel.view.setting;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.msgevent.UpdateBottomView;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.common.BottomItemInfo;
import com.ly.hotel.webagent.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by SHUBEN on 2018/4/16.
 */

public class HomeSortLayout extends LinearLayout {

    private Context context;
    private MyApplication app;
    private Button submitSort;
    private Handler handler;
    private ListView sortList;
    private List<BottomItemInfo> adaList = new ArrayList<>();
    private SortAdapter sortAdapter;

    public HomeSortLayout(Context c) {
        super(c);
        this.context = c;
        this.app = (MyApplication)context.getApplicationContext();
        LayoutInflater.from(getContext()).inflate(R.layout.layout_home_sort, this);
        initView();
    }

    private void initView(){
        submitSort = findViewById(R.id.submit_sort);
        sortList = findViewById(R.id.sort_listView);
        adaList.clear();
        List<BottomItemInfo> bList = app.getBtnItemInfo();
        for (BottomItemInfo bi : bList) {
            if(bi.isEnable()){
                adaList.add(bi);
            }
        }

        if(!TextUtils.isEmpty(app.homeSort)){
            try {
                JSONArray arr = new JSONArray(app.homeSort);
                for (int i = arr.length() -1; i >= 0; i--) {
                    String lan = arr.getString(i);
                    for (BottomItemInfo b : adaList) {
                        if(lan.equals(b.getName())) {
                            adaList.remove(b);
                            adaList.add(0,b);
                            break;
                        }
                    }
                }
            }catch (JSONException e){
                Log.e("HomeSortLayout",e.getMessage());
            }
        }
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0){
                    if(msg.obj != null) {
                        app.homeSort = msg.obj.toString();
                        SharedPreferencesConfig.setHomeSort(context, msg.obj.toString());
                        EventBus.getDefault().post(new UpdateBottomView());
                        ToastUtil.showShortToast(context,"设置成功",3000);
                    }
                }else{
                    ToastUtil.showShortToast(context,"失败",3000);
                }
            }
        };

        sortAdapter = new SortAdapter(context);
        sortList.setAdapter(sortAdapter);
        setListener();
    }

    private void setListener(){
        sortList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BottomItemInfo bottomItemInfo = adaList.get(position);
                adaList.remove(position);
                adaList.add(0,bottomItemInfo);
                sortAdapter.notifyDataSetChanged();
            }
        });
        submitSort.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONArray jArr = new JSONArray();
                for (BottomItemInfo bi : adaList){
                    jArr.put(bi.getName());
                }
                if(jArr.toString().equals(app.homeSort)){
                    ToastUtil.showShortToast(context,"请改变顺序后再提交！",3000);
                }else {
                    setSortMsg(jArr.toString());
                }
            }
        });
    }

    //存储排序信息
    private void setSortMsg(final String str){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
                String myStr = str;
                try {
                    myStr = URLEncoder.encode(str,"utf-8");
                }catch (UnsupportedEncodingException e){
                    e.printStackTrace();
                }
                String request = "filename=HomeIcoSort&content=" + myStr;
                Log.i("httpGet", URL + "?" + request);
                String sendRes = HttpRequest.sendGet(URL, request);
                try {
                    JSONObject jsObj = new JSONObject(sendRes);
                    int code = jsObj.getInt("code");
                    if (code == 200) {
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = str;
                        handler.sendMessage(msg);
                    }else{
                        handler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    class SortAdapter extends BaseAdapter{
        private LayoutInflater mInflater;

        public SortAdapter(Context c) {
            mInflater = LayoutInflater.from(c);
        }

        @Override
        public int getCount() {
            return adaList.size();
        }

        @Override
        public Object getItem(int postion) {
            return adaList.get(postion);
        }

        @Override
        public long getItemId(int postion) {
            return postion;
        }

        @Override
        public View getView(int position, View contentView, ViewGroup arg2) {
            ViewHolder holder;

            if (contentView == null) {

                holder = new ViewHolder();
                contentView = mInflater.inflate(R.layout.home_sort_item, null);
                holder.mTxt = contentView.findViewById(R.id.sort_name);
                holder.mIco = contentView.findViewById(R.id.sort_ico);
                contentView.setTag(holder);
            } else {
                holder = (ViewHolder) contentView.getTag();
            }
            holder.mTxt.setText(adaList.get(position).getShowName());
            holder.mIco.setImageResource(adaList.get(position).getImgRes());
            return contentView;
        }

        class ViewHolder {
            ImageView mIco;
            TextView mTxt;
        }
    }
}
